package com.tfjybj.itoo.exam.message;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author 商俊帅
 * @date 2022/01/10 12:03
 **/
@Service
@Slf4j
public class AliYunMailServiceImpl implements IMailService {

    private final String regionId;

    private final String accessKeyId;

    private final String accessKeySecret;

    private final String fromAddress;

    private final String fromAlias;

    public AliYunMailServiceImpl(@Value("${mail.aliyun.regionId}") String regionId,
                                 @Value("${mail.aliyun.accessKeyId}") String accessKeyId,
                                 @Value("${mail.aliyun.accessKeySecret}") String accessKeySecret,
                                 @Value("${mail.aliyun.account.fromAddress}") String fromAddress,
                                 @Value("${mail.aliyun.account.fromAlias}") String fromAlias){
        this.regionId=regionId;
        this.accessKeyId=accessKeyId;
        this.accessKeySecret=accessKeySecret;
        this.fromAddress=fromAddress;
        this.fromAlias=fromAlias;
    }


    @Override
    public Boolean sendSingleMail(String receiver, String subject, String htmlBody) {
        log.info("start to send mail.receiver:{},subject:{},htmlBody:{}",receiver,subject,htmlBody);
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        SingleSendMailRequest request = new SingleSendMailRequest();

        try{
            //request.setVersion("2017-06-22");// 如果是除杭州region外的其它region（如新加坡region）,必须指定为2017-06-22
            request.setAccountName(fromAddress);
            request.setFromAlias(fromAlias);
            request.setAddressType(1);
            request.setReplyToAddress(true);
            request.setToAddress(receiver);
            //可以给多个收件人发送邮件，收件人之间用逗号分开，批量发信建议使用BatchSendMailRequest方式
            //request.setToAddress("邮箱1,邮箱2");
            request.setSubject(subject);
            //如果采用byte[].toString的方式的话请确保最终转换成utf-8的格式再放入htmlbody和textbody，若编码不一致则会被当成垃圾邮件。
            //注意：文本邮件的大小限制为3M，过大的文本会导致连接超时或413错误
            request.setHtmlBody(htmlBody);
            //SDK 采用的是http协议的发信方式, 默认是GET方法，有一定的长度限制。
            //若textBody、htmlBody或content的大小不确定，建议采用POST方式提交，避免出现uri is not valid异常
            request.setSysMethod(MethodType.POST);
            //开启需要备案，0关闭，1开启
            //request.setClickTrace("0");
            //如果调用成功，正常返回httpResponse；如果调用失败则抛出异常，需要在异常中捕获错误异常码；错误异常码请参考对应的API文档;
            SingleSendMailResponse httpResponse = client.getAcsResponse(request);
            String requestId = httpResponse.getRequestId();
            log.info("end to send mail. receiver:{},subject:{},requestId:{}",receiver,subject,requestId);
            return Boolean.TRUE;
        }catch (ServerException e){
            log.error("errcode:{}",e.getErrCode());
        }catch (ClientException e){
            log.error("errcode:{}",e.getErrCode());
        }
        return Boolean.FALSE;
    }

}
